package com.andy.qhb.game;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.andy.qhb.dao.DaoUtils;
import com.andy.qhb.entity.UsrFriends;
import com.andy.qhb.entity.UsrGameInfo;
import com.andy.qhb.entity.UsrUser;
import com.google.common.collect.Maps;

public class GlobalHttp implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private static Logger logger = LoggerFactory.getLogger(GlobalHttp.class);
	
	/**
	 * 缓存
	 */
	private static Map<Long,GameUser> sessionUserMap = Maps.newConcurrentMap();
	
	public static void initUsers(){
		List<UsrUser> users = DaoUtils.getList(UsrUser.class);
		List<UsrGameInfo> gameInfos = DaoUtils.getList(UsrGameInfo.class);
		List<UsrFriends> friends = DaoUtils.getList(UsrFriends.class);
		
		Map<Long,UsrGameInfo> gameInfosMap = Maps.newHashMap();
		Map<Long,UsrFriends> friendsMap = Maps.newHashMap();
		
		gameInfos.forEach((info)->{
			gameInfosMap.put(info.getUid(), info);
		});
		
		friends.forEach((info)->{
			friendsMap.put(info.getUid(), info);
		});
		
		users.forEach((user)->{
			GameUser gameUser = new GameUser(user);
			gameUser.setGameInfo(gameInfosMap.get(user.getId()));
			gameUser.setFriends(friendsMap.get(user.getId()));
			GlobalHttp.addUser(gameUser);
			
			if(user.getRole() != null && user.getRole() != 0) {
				RobotManager.init(gameUser);
			}
		});
	}
	
	public static void addUser(GameUser gameUser){
		if(logger.isInfoEnabled()){
			logger.info("缓存用户：{}-{}", gameUser.getId(),gameUser);
		}
		sessionUserMap.putIfAbsent(gameUser.getId(), gameUser);
	}

	public static GameUser getUser(Long uid) {
		return sessionUserMap.get(uid);
	}

	public static GameUser removeUser(Long uid){
		return sessionUserMap.remove(uid);
	}
	
}
